<template>
    <HeaderBar :title="$t('home.title')" :hiddenBack="true" @onLogout="onLogout" />
    <view class="home-container main-container">
        <view class="top-panel">
            <view class="item" v-for="item in topList" :key="item.name" @click="toPage(item.path)">
                <wd-icon :name="item.icon" size="40rpx"></wd-icon>
                <view class="name">{{ item.name }}</view>
            </view>
        </view>
        <view class="user-panel">
            <view class="icon" @click="handleUpload">
                <image :src="userInfo.avatar ? userInfo.avatar : Avatar" />
                <view class="photo">
                    <wd-icon name="fill-camera" size="30rpx" color="#fff"></wd-icon>
                </view>
            </view>
            <view class="content">
                <view class="name">{{ userInfo.nickname }}</view>
                <view class="tag" @click="handleCopy">{{$t('home.inviteCode')}} {{ userInfo.inviteCode }}</view>
                <view class="tag">{{$t('home.creditScore')}} {{ userInfo.credit }}</view>
                <view class="tag">{{$t('home.sign')}} {{ userInfo.signCount }}</view>
                <view class="tag star" @click="toPage('/pages/mine/star/index')">
                   {{$t('home.userStar')}}
                    <view class="round">
                        <wd-icon
                            v-for="item in userInfo.level"
                            :key="item"
                            name="star-on"
                            size="16rpx"
                            color="#BF3532"
                        />
                    </view>
                </view>
            </view>
            <view class="btns">
                <view :class="['item', isSignIn && 'grey']" @click="onSignIn">{{isSignIn?$t('home.signed'):$t('home.signIn')}}</view>
                <view class="item" @click="toPage('/pages/mine/wallet/index')">{{$t('home.wallet')}}</view>
            </view>
        </view>
        <view class="column-panel">
            <view class="item" @click="toPage('/pages/activities/index')">
                <image mode="widthFix" class="bg" src="@/static/icon/c1_bg.jpg" />
                <view class="content">
                    <view class="name">{{$t('home.newUser')}}</view>
                    <view class="tips">{{$t('home.userCoupun')}}</view>
                </view>
            </view>
            <view class="item" @click="toPage('/pages/plan/index')">
                <image mode="widthFix" class="bg" src="@/static/icon/c2_bg.jpg" />
                <view class="content">
                    <view class="name">{{$t('home.pushingMarket')}}</view>
                </view>
            </view>
            <view class="item" @click="toPage('/pages/mine/deposit/bonus')">
                <image mode="widthFix" class="bg" src="@/static/icon/c2_bg.jpg" />
                <view class="content">
                    <view class="name">{{$t('home.depositBonus')}}</view>
                </view>
            </view>
            <view class="item" @click="toPage('/pages/about/index')">
                <image mode="widthFix" class="bg" src="@/static/icon/c2_bg.jpg" />
                <view class="content">
                    <view class="name">{{$t('home.aboutUs')}}</view>
                </view>
            </view>
        </view>
        <view class="tab-panel">
            <wd-tabs v-model="active" @change="handleChange" auto-line-width>
                <block v-for="item in tabsList" :key="item.id">
                    <wd-tab :title="`${item.name}`" :name="item.id">
                        <view class="data-view">
                            <view class="title-wrap">
                                <view class="name">{{$t('home.dataOverview')}}</view>
                                <view class="desc">
                                   {{$t('home.dataUpdates')}}
                                    <wd-icon name="refresh" color="#0866ff" size="20rpx" @click="getOrderOverview" />
                                </view>
                            </view>
                            <view class="app-list">
                                <view class="item">
                                    <view class="num">$ {{ formatAmount(orderInfo.investAmount) }}</view>
                                    <view class="content">
                                        <view class="name">{{$t('home.investmentAmount')}}</view>
                                        <view class="icon">
                                            <image mode="heightFix" src="@/static/icon/app1.jpg" />
                                        </view>
                                    </view>
                                </view>
                                <view class="item">
                                    <view class="num">{{ orderInfo.countOrder || 0 }}</view>
                                    <view class="content">
                                        <view class="name">{{$t('home.deliveryOrder')}}</view>
                                        <view class="icon">
                                            <image mode="heightFix" src="@/static/icon/app2.jpg" />
                                        </view>
                                    </view>
                                </view>
                                <view class="item">
                                    <view class="num">$ {{ formatAmount(orderInfo.consumedAmount) }}</view>
                                    <view class="content">
                                        <view class="name">{{$t('home.consumed')}}</view>
                                        <view class="icon">
                                            <image mode="heightFix" src="@/static/icon/app3.jpg" />
                                        </view>
                                    </view>
                                </view>
                                <view class="item">
                                    <view class="num">$ {{ formatAmount(orderInfo.waitConsumedAmount) }}</view>
                                    <view class="content">
                                        <view class="name">{{$t('home.toBeConsumed')}}</view>
                                        <view class="icon">
                                            <image mode="heightFix" src="@/static/icon/app4.jpg" />
                                        </view>
                                    </view>
                                </view>
                                <view class="item">
                                    <view class="num">{{ orderInfo.showCount || 0 }}</view>
                                    <view class="content">
                                        <view class="name">{{$t('home.impressions')}}</view>
                                        <view class="icon">
                                            <image mode="heightFix" src="@/static/icon/app5.jpg" />
                                        </view>
                                    </view>
                                </view>
                                <view class="item">
                                    <view class="num">{{ orderInfo.clickCount || 0 }}</view>
                                    <view class="content">
                                        <view class="name">{{$t('home.clicks')}}</view>
                                        <view class="icon">
                                            <image mode="heightFix" src="@/static/icon/app6.jpg" />
                                        </view>
                                    </view>
                                </view>
                                <view class="item">
                                    <view class="num">$ {{ formatAmount(orderInfo.totalIncome) }}</view>
                                    <view class="content">
                                        <view class="name">{{$t('home.advertising')}}</view>
                                        <view class="icon">
                                            <image mode="heightFix" src="@/static/icon/app7.jpg" />
                                        </view>
                                    </view>
                                </view>
                                <view class="item">
                                    <view class="num">$ {{ formatAmount(orderInfo.totalProfit) }}</view>
                                    <view class="content">
                                        <view class="name">{{$t('home.profit')}}</view>
                                        <view class="icon">
                                            <image mode="heightFix" src="@/static/icon/app8.jpg" />
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </wd-tab>
                </block>
            </wd-tabs>
        </view>
        <view class="faq-panel">
            <view class="title">{{$t('home.faqs')}}</view>
            <view class="list">
                <view class="item" v-for="item in faqList" :key="item.name" @click="toFaq(item)">
                    <view class="name">{{ item.name }}</view>
                    <view class="arrow">
                        <wd-icon name="arrow-right" color="rgb(101, 103, 106)" size="30rpx"></wd-icon>
                    </view>
                </view>
            </view>
        </view>
    </view>
    <uni-popup ref="serviceRef">
        <Service @onClose="onClose" />
    </uni-popup>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad, onHide } from '@dcloudio/uni-app';
import Service from '@/components/Service/index';
import HeaderBar from '@/components/HeaderBar/index';
import { NavigateTo, setStorage, showToast, getStorage, formatAmount, copyToClipboard } from '@/utils/common';
import { formatDate } from '@/utils/date';
import { toLang } from '@/utils/lang';
import Avatar from '@/static/icon/avatar.jpg';
import { memberInfo, updateAvatar, getCommonEnums } from '@/api/mine';
import { addSignIn } from '@/api/signIn';
import { orderOverview } from '@/api/order';
const serviceRef = ref(null) as any;
const userInfo = ref({}) as any;
const isSignIn = ref<boolean>(false);
const orderInfo = ref({}) as any;

const topList = ref([
    {
        icon: 'chevron-up-rectangle',
        name: toLang('home.coupons'),
        path: '/pages/coupons/index'
    },
    {
        icon: 'a-rootlist',
        name: toLang('home.feedback'),
        path: '/pages/fackbook/index'
    },
    {
        icon: 'lock-on',
        name: toLang('home.loginPwd'),
        path: '/pages/login/password'
    },
    {
        icon: 'service',
        name: toLang('home.service'),
        path: 'service'
    }
]);
const tabsList = ref([
    {
        id: '1',
        name: toLang('home.today')
    },
    {
        id: '2',
        name: toLang('home.week')
    },
    {
        id: '3',
        name: toLang('home.month')
    },
    {
        id: '4',
        name: toLang('home.all')
    }
]);

const faqList = ref([
        {
            name: toLang('home.faq1Name'),
            content:toLang('home.faq1Content')
        },
        {
            name: toLang('home.faq2Name'),
            content:toLang('home.faq1Content')
        },
        {
            name: toLang('home.faq3Name'),
            content:toLang('home.faq1Content')
        },
        {
            name: toLang('home.faq4Name'),
            content:toLang('home.faq1Content')
        },
        {
            name: toLang('home.faq5Name'),
            content:toLang('home.faq1Content')
        },
        {
            name: toLang('home.faq6Name'),
            content:toLang('home.faq1Content')
        }
        
    ]);

const active = ref('1');
const timer = ref(null) as any;

onLoad(() => {
    getUserInfo();
    getCommonEnumsInfo();
    getOrderOverview();
});

onHide(() => {
    clearAutoRefresh();
});

//获取用户信息
const getUserInfo = async () => {
    const user = await memberInfo();
    const data = {
        ...user.data,
        avatar: user.data.avatar ? user.data.filePreviewUrl + '/' + user.data.avatar : ''
    };
    setStorage('user', data);
    userInfo.value = data;
    isSignIn.value = data.todaySigned;
};

//获取订单概览
const getOrderOverview = async () => {
    let startTime = formatDate(new Date(), 'YYYY-MM-DD') + ' 00:00:00';
    let endTime = formatDate(new Date(), 'YYYY-MM-DD') + ' 23:59:59';
    switch (active.value) {
        case '2':
            startTime =
                formatDate(new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000), 'YYYY-MM-DD') + ' 00:00:00';
            break;
        case '3':
            startTime =
                formatDate(new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000), 'YYYY-MM-DD') + ' 00:00:00';
            break;
        case '4':
            startTime = '';
            endTime = '';
            break;
        default:
            break;
    }
    const res = await orderOverview({ startTime, endTime });
    if (res.code !== 200) {
        return;
    }
    orderInfo.value = res.data || {};

    if (timer.value) {
        timer.value = null;
        clearTimeout(timer.value);
    }
    //30分钟自动刷新一次
    timer.value = setTimeout(() => {
        getOrderOverview();
    }, 1000 * 30);
};

//清除自动刷新
const clearAutoRefresh = () => {
    if (timer.value) {
        timer.value = null;
        clearTimeout(timer.value);
    }
};

//签到
const onSignIn = async () => {
    if (isSignIn.value) {
        return;
    }
    const res = await addSignIn({ memberId: userInfo.value.id, signDate: formatDate() });
    if (res.code !== 200) {
        return;
    }
    isSignIn.value = true;
    getUserInfo();
    showToast({ title: 'SignIn Success' });
};

//复制邀请码
const handleCopy = () => {
    copyToClipboard(userInfo.value.inviteCode);
};

//上传图片
const handleUpload = () => {
    uni.chooseFile({
        count: 1, //默认9
        success: async (e) => {
            let file: any = null;
            // 判断 tempFiles 是否为数组，并取第一个文件
            if (Array.isArray(e.tempFiles)) {
                file = e.tempFiles[0];
            } else {
                file = e.tempFiles;
            }
            const res = await updateAvatar({ filePath: file.path });
            if (res.code !== 200) {
                return;
            }
            userInfo.value.avatar = userInfo.value.filePreviewUrl + res.data;
            setStorage('user', userInfo.value);
            showToast({ title: 'Upload Success' });
        }
    });
};

//切换tab
const handleChange = (e) => {
    active.value = e.name;
    getOrderOverview();
};

//界面跳转
const toPage = (url: string) => {
    if (url === 'service') {
        serviceRef.value.open('center');
        return;
    }
    clearAutoRefresh();
    NavigateTo(url);
};

//跳转到faq详情
const toFaq = (row: any) => {
    clearAutoRefresh();
    setStorage('faqDetail', row);
    NavigateTo('/pages/mine/faq/detail');
};

//关闭服弹窗
const onClose = () => {
    serviceRef.value.close();
};

// 获取通用码值
const getCommonEnumsInfo = async () => {
    const commonEnums = getStorage('commonEnums') || false;
    if (commonEnums) {
        return;
    }
    const res = await getCommonEnums();
    if (res.code !== 200) {
        return;
    }
    setStorage('commonEnums', res.data);
};

//登出
const onLogout = () => {
    clearAutoRefresh();
};
</script>

<style lang="scss">
@import '@/styles/home.scss';
</style>
